"use strict";
const { Model } = require("sequelize");
const { IdGenerator } = require("../utils/idGenerator");
module.exports = (sequelize, DataTypes) => {
  class Category extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      Category.hasMany(models.Course, {
        foreignKey: "categoryId",
        as: "courses",
      });
    }
  }

  Category.init(
    {
      id: {
        type: DataTypes.INTEGER.UNSIGNED, // 无符号整数类型
        allowNull: false,
        primaryKey: true,
        defaultValue: function () {
          return IdGenerator.getNextID(); // 使用封装的ID生成方法
        },
      },
      name: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          notNull: { msg: "用户名必须填写。" },
          notEmpty: { msg: "用户名不能为空。" },
          len: { args: [2, 45], msg: "用户名长度必须是2~45之间。" },
          async isUnique(value) {
            const categories = await Category.findOne({
              where: { name: value },
            });
            if (categories) {
              throw new Error("名称已存在,请选择其他名称。");
            }
          },
        },
      },
      rank: {
        type: DataTypes.INTEGER,
        allowNull: false,
        validate: {
          notNull: { msg: "排序必须填写。" },
          notEmpty: { msg: "排序不能为空。" },
          isInt: { msg: "排序必须为整数。" },
          isPositive(value) {
            if (value <= 0) {
              throw new Error("排序必须是正整数。");
            }
          },
        },
      },
      createdAt: {
        allowNull: false,
        type: DataTypes.DATE,
      },
      updatedAt: {
        allowNull: false,
        type: DataTypes.DATE,
      },
    },
    {
      sequelize,
      modelName: "Category",
    },
  );
  return Category;
};
